package org.paraj.sync;

import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * User: piotrga
 * Date: Oct 16, 2008
 * Time: 10:25:15 PM
 */
public class SingleJVMResourceMonitor implements ResourceMonitor{
    private boolean fair;

    public SingleJVMResourceMonitor() {
        this(true);
    }

    public SingleJVMResourceMonitor(boolean fair) {
        this.fair = fair;
    }

    Map<Object, ReentrantReadWriteLock> locks = new WeakHashMap<Object, ReentrantReadWriteLock>(){
        public synchronized ReentrantReadWriteLock get(Object key) {
            ReentrantReadWriteLock res = super.get(key);
            if (res == null){
                res = new ReentrantReadWriteLock(fair);
                super.put(key, res);
            }
            return res;
        }
    };

    public Lock writerEnters(Object key) {
        ReentrantReadWriteLock.WriteLock writeLock = locks.get(key).writeLock();
        writeLock.lock();
        return writeLock;
    }

    public Lock readerEnters(Object key) {
        ReentrantReadWriteLock.ReadLock readLock = locks.get(key).readLock();
        readLock.lock();
        return readLock;
    }
}
